import React, { memo, useRef, useState } from 'react'
import classNames from 'classnames'
import { useScrollPosition } from '@/hooks/useScrollPosition'
import { ThemeProvider } from 'styled-components'
import HeaderCenter from './c-cpns/headerCenter'
import HeaderLeft from './c-cpns/headerLeft'
import HeaderRight from './c-cpns/headerRight'
import { HeaderWarpper, SearchAreaWrapper } from './style'

const AppHeader = memo((props) => {
  const { headerConfig } = props
  const { isFixed, topAlpha } = headerConfig
  const [isSearch, setIsSearch] = useState(false)

  const { scrollY } = useScrollPosition()
  const prevY = useRef(0)
  if (!isSearch) prevY.current = scrollY
  if (isSearch && Math.abs(scrollY - prevY.current) > 30) setIsSearch(false)
  
  const isAlpha = topAlpha && scrollY === 0

  return (
    <ThemeProvider theme={{isAlpha}}>
      <HeaderWarpper className={classNames({"fixed": isFixed})}>
        <div className="content">
          <div className="top">
            <HeaderLeft />
            <HeaderCenter isSearch={isAlpha || isSearch} searchBarClick={e => setIsSearch(!isSearch)} />
            <HeaderRight />
          </div>
          <SearchAreaWrapper isSearch={isAlpha || isSearch} />
        </div>
        {isSearch && <div className="cover" onClick={e => setIsSearch(false)}></div>}
      </HeaderWarpper>
    </ThemeProvider>
  )
})

export default AppHeader